package com.link2room.blaster.common;

import com.link2room.common.dto.result.base.BaseDto;
import com.link2room.blaster.entity.MsgTemplate;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateNotFoundException;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

/**
 * Created by LN on 2016/9/13.
 */
public class FreemarkerUtil {
    private static Configuration cfg = new Configuration();

    /**
     * 设置模板
     * @param template
     */
    private static synchronized void putTemplate(MsgTemplate template){
        StringTemplateLoader stringLoader = new StringTemplateLoader();
        String key = generateTemplateKey(template);
        stringLoader.putTemplate(key,template.getTemplate());
        cfg.setTemplateLoader(stringLoader);
    }
    private static Template getTemplate(MsgTemplate msgTemplate) throws IOException {
        String key = generateTemplateKey(msgTemplate);

        Template template = null;
        try {
            template = cfg.getTemplate(key, "utf-8");
        } catch (TemplateNotFoundException e) {
            putTemplate(msgTemplate);
            template = cfg.getTemplate(key, "utf-8");
        }
        return template;
    }
    private static String generateTemplateKey(MsgTemplate template){
        return template.getLhotelGroupCode()+template.getLhotelCode()+template.getChannel()+template.getCode();
    }

    /**
     * 模板替换
     * @param msgTemplate
     * @param dateModule
     * @return
     * @throws Exception
     */
    public static String getMsg(MsgTemplate msgTemplate, Map<String,Object> dateModule) throws Exception {
        Template template = getTemplate(msgTemplate);
        StringWriter writer = new StringWriter();
        template.process(dateModule, writer);
        return writer.toString();
    }
    /**
     * 模板替换
     * @param msgTemplate
     * @param dto
     * @return
     * @throws Exception
     */
    public static String getMsg(MsgTemplate msgTemplate, BaseDto dto) throws Exception {
        Map<String, Object> dateModule = dto.toMap();
        Template template = getTemplate(msgTemplate);
        StringWriter writer = new StringWriter();
        template.process(dateModule, writer);
        return writer.toString();
    }

}
